package com.cangchu.db.domain;

import android.content.Context;
import com.cangchu.util.FileUtils;
import com.cangchu.util.GsonUtil;
import com.cangchu.util.HttpUtils;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import cz.msebera.android.httpclient.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据仓库类，使用单例模式，将数据保存在内存当中。
 * Created by Administrator on 2016/10/28.
 */
public class DataRep {

    private static final String FILENAME = "goods.json";

    //单例返回的实例对象
    private static DataRep instance;
    private Context mAppContext;
    //单例中管理的各类数据
    private List<Goods> goodses;
    private List<Batch> batches;

    private FileUtils utils;

    private DataRep(Context appContext) {
        mAppContext = appContext;
        utils = new FileUtils(appContext);
        initData();
    }

    private void initData() {
        try {
            goodses = GsonUtil.toEntity(utils.read(FILENAME), new TypeToken<List<Goods>>() {});
            HttpUtils.post(mAppContext, "http://121.43.189.138:6000/batch", new RequestParams("version", "1"), new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    try {
                        batches = GsonUtil.toEntity(response.getJSONArray("data").toString(), new TypeToken<List<Batch>>() {
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (IOException e) {
            goodses = new ArrayList<>();
        }
    }

    public static DataRep getInstance(Context context) {
        if (instance == null) {
            instance = new DataRep(context);
        }
        return instance;
    }

    public List<Goods> getGoodses() {
        return goodses;
    }

    public List<Batch> getBatches() {
        return batches;
    }

    public void save(Goods entity) {
        for (Goods goods : goodses) {
            if (goods.getUuid().equals(entity.getUuid())) {
                goodses.remove(goods);
                break;
            }
        }
        goodses.add(entity);
    }

    public void delete(Goods entity) {
        goodses.remove(entity);
    }


    public Goods getGoods(String uuid) {
        for (Goods goods : goodses) {
            if (goods.getUuid().toString().equals(uuid)) {
                return goods;
            }
        }
        return null;
    }

    /**
     * 将管理的所有数据进行实例化，保存到json文件中【可能需要管理多个json文件】
     */
    public void serializableData() {
        try {
            utils.save(FILENAME, GsonUtil.toJson(goodses));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
